﻿using Microsoft.AspNetCore.Mvc;
using Mozhi.Abp.Domain.AuthorCenter;
using Mozhi.Abp.Domain.AuthorCenter.Repositories;
using Swashbuckle.AspNetCore.SwaggerGen;
using System.Threading.Tasks;
using Volo.Abp.AspNetCore.Mvc;
using Volo.Abp.Guids;

namespace mozhi.smarterp.Business.Controllers;

public class HomeController : AbpController
{
    private IGuidGenerator _guidGenerator;
    private SwaggerGenerator _swaggerGenerator;
    private IApiMetadataRepository _apiMetadataRepository;

    public HomeController(IGuidGenerator guidGenerator, SwaggerGenerator swaggerGenerator , IApiMetadataRepository apiMetadataRepository)
    {
        _guidGenerator = guidGenerator;
        _swaggerGenerator = swaggerGenerator;
        _apiMetadataRepository = apiMetadataRepository;
    }

    public ActionResult Index()
    {
        return Redirect("~/swagger");
    }

    public async Task<ActionResult> GenerateApiMatedata()
    {
        var apiDocument = _swaggerGenerator.GetSwagger("v1", "", "");

        var scope = "Business";

        if (apiDocument == null || apiDocument.Paths == null)
            return Ok();

        foreach (var path in apiDocument.Paths)
        {
            foreach (var operation in path.Value.Operations)
            {
                var apiMetadata = new ApiMetadata(path.Key, operation.Key.ToString(), scope);

                await _apiMetadataRepository.InsertAsync(apiMetadata);
            }
        }

        return Ok();
    }
}
